;
(function() {
	var ACCOUNTID = hlUrlUtil.GetQueryString('businessId'); //账单id
	var CONTRACTID; //合同id

	Array.prototype.removeRepeatBuildingAndFLoor = function() {
		var res = [this[0]];
		for (var i = 1; i < this.length; i++) {
			var repeat = false;
			for (var j = 0; j < res.length; j++) {
				if (this[i].buildingName == res[j].buildingName && this[i].floorNum == res[j].floorNum) {
					repeat = true;
				}
			}
			if (!repeat) {
				res.push(this[i]);
			}
		}
		return res;
	};

	new Vue({
		el: '#bill-detail-flow',
		data: {
			menuList: [],
			menuList: [
				{name: '账单信息', disabled: true},
				{name: '流程信息', disabled: true},
			],
			tableSelected : '账单信息',
			flowState: hlUrlUtil.GetQueryString('page') === 'XQ' ? false : true,
			billid: ACCOUNTID,
			contractid: CONTRACTID,
			taskId:hlUrlUtil.GetQueryString('taskId'),
			bpmId:hlUrlUtil.GetQueryString('bpmId'),
			contractData: {
				ot: [],
				st: []
			},
			billData: {
				expenses: [],
				transactions: [],
				invoiceInfos: [],
				carryOverInfos: []
			},
			userid: JSON.parse(window.localStorage.getItem('userMes')).id,
			bpm:{},  // 工作流程信息
			bpmList:[], // 工作流程列表
			editFlag: true,
			temporary: 0,
			projectIds:hlUrlUtil.GetQueryString('projectIds'),
			permissions: JSON.parse(localStorage.getItem('permissions')),
			costItem: [],
			fPData: [],
			fpPut: [],
			fpFlag: false,
			closeFlag: false,
			memo: {
				content: '',
				flag: false
			},
			proid: '',			
			Fp: [],
			jlFp: [],
			st: [], // 车位
			wp: [], // 工位
			stTotalNum: 0, // 车位总数
			wpTotalNum: 0, // 工位总数
			totalArea: 0, // 单元总面积
			building: [], // 楼宇信息
			projectName: null, // 项目名
			unitOpenFlag: false,
			wpOpenFlag: false,
			stOpenFlag: false,
			CZOpenFlag: false,
			printflag: true,
			isEditCountMes: false,
			receiptDeadlineDate: null,
			aa: null,
			logData: [],
			IsCompareRentAmtFlag: false,
			isPaymantflag: false
		},
		filters: {
			timestamp: function(time) {
				return hlDateUtil.formatUTCDate(time, 'yyyy-MM-dd')
			},
			formatUTCDate: function(time) {
				return hlDateUtil.formatUTCDate(time, 'yyyy-MM-dd HH:mm:ss')
			},
			billState: function(state) {
				if (!state) return '';
				return hlCodeConvert.billPaymentState(state)
			},
			toFixed2: function(n) {
				return Number(n).toFixed(2)
			},
			billPayWay: function(state) {
				return hlCodeConvert.billPayWay(state)
			},
			//千分位
			formatNum: function(n) {
				return hlNumberUtil.formatNum(n)
			},
			absNum: function(n) {
				return Math.abs(n)
			}
		},
		computed: {
			temporarys: function() {
				let res = 0;
				for (var i = 0; i < this.billData.expenses.length; i++) {
					if (this.billData.expenses[i].expenseType === 'T') {
						res++
					}
				}
				return res
			},
			fPDataNum: function() {
				var result = 0;
				for (var i = 0; i < this.fPData.length; i++) {
					if (this.fPData[i].expenseType === 'T') {
						result++
					}
				}
				return result
			},
			//应收本金
			totalYS: function() {
				var result = 0; //总和
				var IS = 0; //已收款
				this.billData.expenses.map(function(item) {
					if (Number(item.amountReceived) > 0) {
						result += Number(item.amountReceived)
					}
				})
				return result
			},
			//已收本金
			totalIS: function() {
				var result = 0; //总和
				this.billData.expenses.map(function(item) {
					result += Number(item.amountPayed);
				})
				return result
			},
			//减免本金
			totalJM: function() {
				var result = 0; //总和
				this.billData.expenses.map(function(item) {
					result += Number(item.amountDerate);
				})
				return result
			},
			//结转抵扣 (应收)
			carryOverTotalAmount: function() {
				var result = 0; //总和
				this.billData.expenses.map(function(item) {
					if (item.carryOverTotalAmount > 0 && item.amountReceived > 0) {
						result += Number(item.carryOverTotalAmount);
					}
				})
				return result
			},
			//本次应收本金
			totalBCYS: function() {
				var result = 0; //总和
				result = this.totalYS - this.totalIS - this.totalJM - this.carryOverTotalAmount;
				return result
			},
			//应收滞纳金
			totalYSznj: function() {
				var result = 0; //总和
				var IS = 0; //已收款
				this.billData.expenses.map(function(item) {
					result += Number(item.lateFeeReceived)
				})
				return result
			},
			//已收滞纳金
			totalISznj: function() {
				var result = 0; //总和
				this.billData.expenses.map(function(item) {
					result += Number(item.lateFeePayed);
				})
				return result
			},
			//减免滞纳金
			totalJMznj: function() {
				var result = 0; //总和
				this.billData.expenses.map(function(item) {
					result += Number(item.lateFeeDerate);
				})
				return result
			},
			//本次应收滞纳金
			totalBCYSznj: function() {
				var result = 0; //总和
				// result = this.totalYSznj - this.totalISznj - this.totalJMznj;
				this.billData.expenses.map(function(item) {
					result += Number(item.lateFeeTPay)
				})
				return result
			},
			//本次应退
			totalYT: function() {
				var result = 0; //总和
				this.billData.expenses.map(function(item) {
					result += Math.abs(Number(item.amountRefund))
				})
				return result
			},
			//已退本金
			totalIT: function() {
				var result = 0; //总和
				this.billData.expenses.map(function(item) {
					result += Math.abs(Number(item.refundPayed))
				})
				return result
			},
			//结转抵扣 (应退)
			carryOverTotalAmountYt: function() {
				var result = 0; //总和
				this.billData.expenses.map(function(item) {
					result += Math.abs(item.refundCarryover);
				})
				return result
			},
			//本次应退
			totalBCYT: function() {
				var result = 0; //总和
				result = this.totalYT - this.totalIT - this.carryOverTotalAmountYt
				return result
			},
			//本次应收合计
			totalYSHJ: function() {
				var result = 0; //总和
				result = this.totalBCYS + this.totalBCYSznj - this.totalBCYT;
				if (this.totalNum == 1) {
					this.txs[0]['amountTPay'] = Number(result).toFixed(2);
				}
				this.totalNum++;
				return Number(result).toFixed(2)
			},

			cumulation: function() {
				var result = 0;
				this.txs.map(function(item) {
					result += Number(hlNumberUtil.formatThousandsNum(item.amountTPay))
				})
				return Number(result).toFixed(2);
			}
		},
		methods: {
			
			// 获取流程详情数据
			getBpmDetailData:function () {
			  var self = this;
			  hlhttp.get({
			    url:'bpm',
			    data:{
			      bpm_key:'BT',
			      bpm_id: this.bpmId
			    },
			    success:function (data) {
			      var newArr = data;
			      var bpdefId = data.bpdefId || 0
			
						self.approveFlag = data.approveFlag
			      self.$set(self.$data, 'bpm', newArr)
			      self.getFlowNodeData(bpdefId)
			    }
			  })
			},
			// 获取流程节点数据
			getFlowNodeData:function (id) {
			  var self = this;
			  // 当所传id为0时展示最初始的业务节点图   ====>  开始 ----- 合同审核  ----- 结束
			  if(id === 0){
			    var nodeData = [{
			      name:'合同审核'
			    }]
			    self.flowNode = nodeData;
			
			  }
			  if(id !== 0){
			    hlhttp.get({
			      url:'bpdef_phases',
			      data:{'bpdef_id':id},
			      success:function(data){
			        self.flowNode = data
			      }
			    })
			  }
			},
			calculateTimeDifference:function(item1,item2){
			  return hlDateUtil.timeDifference(item1,item2)
			},
			
			handleTabClick (res) {
				console.log(this.queryParams)
				this.tableSelected = res.name
				// if (res.name == '流程信息') this.getBpmDetailData()
			},

			// 通过审核
			passAudit: function() {
				var self = this;
				hllayer.prompt({
					title: '审核通过', // 标题  默认为空
					placeholder: '审核通过原因说明（非必填）',
					leftBtn: '提交',
					confirm: function(mes) {
						$('.hllayer-mask, .hllayer-view').remove()
						hlhttp.put({
							url: 'bpm/_pass',
							data: {
								bpm_key: 'BT',
								task_id: self.taskId,
								bpm_id: self.bpmId,
								memo: mes || '#',
								state: self.billData.billState
							},
							success: function(data) {
								hl.toast('审核通过')
								hllayer.close();
								hlUrlUtil.goTo('todo', {
									stateName: 'BT',
									projectIds: self.projectIds,
									ddtab: true
								})
							}
						})
					}
				})
			},
			// 未通过审核
			notPassAudit: function() {
				var self = this;
				hllayer.prompt({
					title: '审核不通过',
					placeholder: '审核不通过原因说明（必填）',
					leftBtn: '提交',
					confirm: function(mes) {
						if (!mes) {
							hl.toast('请填写审核不通过的原因')
							return
						}
						hlhttp.put({
							url: 'bpm/_reject',
							data: {
								task_id: self.taskId,
								bpm_id: self.bpmId,
								memo: mes,
								state: self.billData.billState
							},
							success: function(data) {
								hl.toast('审核不通过')
								hllayer.close();
								hlUrlUtil.goTo('todo', {
									stateName: 'BT',
									projectIds: self.projectIds,
									ddtab: true
								})

							}
						})
					}
				})
			},
			// 撤回
			withdrawCH: function() {
				var self = this;
				hllayer.confirm('撤回后，流程将立即终止', function() {
					hlhttp.delete({
						url: 'bpm/_withdraw?bpm_id=' + self.bpmId,
						success: function() {
							hl.toast('撤回成功')
							hlUrlUtil.goTo('myFlowList', {
								projectIds: self.projectIds,
								ddtab: true
							})
						}
					})
				})
			},
			//催办
			cuiban: function () {
				var self = this;
				hlhttp.get({
					url: 'bpm/urge/time',
					data: {bpm_id: self.bpmId},
					success: function (res) {
						hllayer.promptSm({
							title:'催办',
							leftBtn:'确定',
							subTitle: '本操作将给处理人发送一条微信消息！',
							tips: '距离上次催办'+time(res.time),
							confirm:function (msg) {
								hlhttp.put({
									url: 'bpm/urge',
									data: {bpm_id: self.bpmId, task_id: self.taskId, memo: msg || '#'},
									success: function () {
										hl.toast('发送成功')
										hlUrlUtil.goTo('myFlowList', {
											projectIds: self.projectIds,
											ddtab: true
										})
									}
								})
							}
						})
					}
				})
			},

			// 获取合同单元信息
			getContractUnitsData: function() {
				var self = this;
				hlhttp.get({
					url: 'contract/units',
					data: {
						id: CONTRACTID
					},
					success: function(data) {
						// 单元
						var buildingData = self.dealWithUnitData(data)
						self.totalArea = buildingData.totalArea
						self.building = buildingData.building
						// 车位
						self.st = [];
						self.wp = [];
						var stTotalNum = 0;
						var wpTotalNum = 0;
						data.map(function(item) {
							if (item.positions && item.unitType === 'ST') {
								stTotalNum = stTotalNum + item.positions.length;
								item['num'] = item.positions.length;
								self.st.push(item)
							}
							if (item.positions && item.unitType === 'WP') {
								wpTotalNum = wpTotalNum + item.positions.length;
								item['num'] = item.positions.length;
								self.wp.push(item)
							}
						})
						self.stTotalNum = stTotalNum;
						self.wpTotalNum = wpTotalNum;
					}
				})
			},
			// 单元数据去重整合处理
			dealWithUnitData: function(unitsData) {
				// 去除含有工位车位的单元
				var units = [];
				unitsData.map(function(_item) {
					if (_item.positions.length === 0) {
						units.push(_item)
					}
				})
				if (units.length === 0) {
					return {
						building: [],
						totalArea: 0
					}
				}
				// 合并单元项
				var unit = [];
				var totalArea = 0;
				for (var i = 0; i < units.length; i++) {
					unit.push({
						buildingName: units[i].buildingName,
						floorNum: units[i].floorNum,
						floorName: units[i].floorName,
						unit: []
					})
				}
				var unitArr = unit.removeRepeatBuildingAndFLoor()
				for (var z = 0; z < unitArr.length; z++) {
					for (var m = 0; m < units.length; m++) {
						if (units[m].buildingName == unitArr[z].buildingName && units[m].floorNum == unitArr[z].floorNum) {
							unitArr[z].unit.push(units[m].unitName + '(' + hlNumberUtil.formatNum(units[m].unitAcreage) + 'm²)')
							totalArea = totalArea + Number(units[m].unitAcreage)
						}
					}
				}
				// 合并楼层项
				var building = [];
				for (var j = 0; j < unitArr.length; j++) {
					building.push({
						buildingName: unitArr[j].buildingName,
						floor: []
					})
				}
				var buildingArr = hlArrayUtil.removeRepeat(building, 'buildingName')
				for (var k = 0; k < buildingArr.length; k++) {
					for (var n = 0; n < unitArr.length; n++) {
						if (unitArr[n].buildingName == buildingArr[k].buildingName) {
							buildingArr[k].floor.push({
								'floorNum': unitArr[n].floorNum,
								'floorName': unitArr[n].floorName,
								'unit': unitArr[n].unit
							})
						}
					}
				}
				return {
					building: buildingArr,
					totalArea: totalArea
				}
			},
			// 查看出租资源详情信息
			checkDetailMes: function(type) {
				var self = this;
				if (type === 'unit') {
					if (self.unitOpenFlag === true) {
						self.unitOpenFlag = false
						return false
					}
					if (self.unitOpenFlag === false) {
						self.unitOpenFlag = true
						return false
					}
				}
				if (type === 'wp') {
					if (self.wpOpenFlag === true) {
						self.wpOpenFlag = false;
						return false;
					}
					if (self.wpOpenFlag === false) {
						self.wpOpenFlag = true
						return false;
					}
				}
				if (type === 'st') {
					if (self.stOpenFlag === true) {
						self.stOpenFlag = false
						return false;
					}
					if (self.stOpenFlag === false) {
						self.stOpenFlag = true
						return false;
					}
				}
			},
			//获取合同信息
			getContractData: function() {
				var _this = this;
				contract.formatUnitData(CONTRACTID, function(data) {
					_this.contractData = data
				})
			},
			//跳转营业额详情
			gotoCommisson() {
				hlUrlUtil.goTo('commissionDetail', {
					'id': ACCOUNTID,
					ddtab: true
				})
			},
			//获取意向详情
			getYxInfo(id) {
				var self = this;
				hlhttp.get({
					url: 'contract/intent',
					data: {
						id: id
					},
					success: (data) => {
						data.projectInfo.units.map(item => {
							item.positions = [];
							item.floorName = item.floorNum
						})
						this.contractData.zlfCompany = data.zlfInfo.zlfName
						this.contractData.projectName = data.projectInfo.projectName
						var buildingData = this.dealWithUnitData(data.projectInfo.units)
						this.totalArea = buildingData.totalArea
						this.building = buildingData.building;
						this.st = [];
						this.wp = [];
						var stTotalNum = 0;
						var wpTotalNum = 0;
						//车位
						let newStArr = hlArrayUtil.removeRepeat(data.projectInfo.stops, 'unitId'),
							newStIds = [];
						newStArr.map(item => {
							item.floor = item.floorNum;
							item.floorName = item.floorNum
							item.positions = []
						})
						data.projectInfo.stops.map(item => {
							newStIds.push(item.stopId)
							newStArr.map(item1 => {
								if (item.unitId == item1.unitId) {
									stTotalNum++
									item1.positions.push({
										positionName: item.stopName,
										positionId: item.stopId
									})
								}
							})
						})
						self.st = newStArr;
						let newWpArr = hlArrayUtil.removeRepeat(data.projectInfo.wps, 'unitId'),
							newWpIds = [];
						newWpArr.map(item => {
							item.floor = item.floorNum
							item.positions = []
						})
						data.projectInfo.wps.map(item => {
							newWpIds.push(item.wpId)
							newWpArr.map(item1 => {
								if (item.unitId == item1.unitId) {
									wpTotalNum++
									item1.positions.push({
										positionName: item.wpName,
										positionId: item.wpId
									})
								}
							})
						})
						this.wp = newWpArr
						self.stTotalNum = stTotalNum;
						self.wpTotalNum = wpTotalNum;
					}
				})
			},
			//获取账单信息
			getBillData: function() {
				var _this = this;
				hlhttp.get({
					url: 'bill,expenses,transactions',
					data: {
						bill_id: ACCOUNTID
					},
					success: function(data) {
						if (data.intentId) _this.getYxInfo(data.intentId)
						CONTRACTID = data.contractId
						if (CONTRACTID) {
							_this.contractid = CONTRACTID
							_this.getContractData()
							_this.getContractUnitsData()
						}

						data.expenses.map(item => {
							item.derate_expense_update_flag = item.derateExpenseUpdateFlag && item.derateExpenseUpdateFlag == 'Y' ?
								'Y' : 'N';
							item.derate_late_fee_update_flag = item.derateLateFeeUpdateFlag && item.derateLateFeeUpdateFlag == 'Y' ?
								'Y' : 'N';
							item.late_fee_received_update_flag = item.lateFeeReceivedUpdateFlag && item.lateFeeReceivedUpdateFlag ==
								'Y' ? 'Y' : 'N';
							item.expense_name_update_flag = item.nameUpdateFlag && item.nameUpdateFlag == 'Y' ? 'Y' : 'N';
							item.expense_amount_update_flag = item.amountReceiveUpdateFlag && item.amountReceiveUpdateFlag == 'Y' ?
								'Y' : 'N';
							item.expense_memo_update_flag = item.memoUpdateFlag && item.memoUpdateFlag == 'Y' ? 'Y' : 'N';
							item.lateFeeTPayUpdateFlag = item.lateFeeTPayUpdateFlag && item.lateFeeTPayUpdateFlag == 'Y' ? 'Y' :
								'N';
						})

						_this.billData = data;
						_this.proid = data.projectId;
						_this.receiptDeadlineDate = hlDateUtil.formatUTCDate(data.deadlineDate, 'yyyy-MM-dd')
					}
				})
			},
			//获取日志详情
			getlogData() {
				var that = this
				hlhttp.get({
					url: 'bill/logs',
					data: {
						bill_id: ACCOUNTID
					},
					success: function(data) {
						that.logData = data.groupLogs
						that.logData.forEach(item => {
							if (item.operationName == '编辑账单费项') {
								item.logRecords.forEach(item1 => {
									item1.list = []
									for (var i = 0; i < item1.rowData.length; i += 3) {
										item1.list.push(item1.rowData.slice(i, i + 3));
									}
								})
							}
						})
					}
				})
			},


			getResult(code) {
				hlhttp.get({
					url: 'tenant/bills/batch_reminder/fail_cause_list',
					data: {
						'msg_send_operate_group': code
					},
					success: function(res) {
						let data = JSON.parse(res[0].resultDetail)
						hl.toast(data.failure_reasons[0])
					}
				})
			},


			//大图浏览
			getBigPic: function(img) {
				var temp = img ? img.split(',') : null;
				$.imageShow(temp)
			},
			//说明a
			getMemo: function(content, flag) {
				this.memo = {
					content: content,
					flag: flag
				}
			},
			// 获取项目模板列表
			getProjectModuleList: function(fn) {
				var self = this;
				hlhttp.get({
					url: 'project/print_template_list',
					data: {
						'project_id': self.proid
					},
					success: function(res) {
						var isUserDefault = false; // 判断是否存在用户默认模版
						res.forEach((el, i) => {
							if (el.type == 'C') isUserDefault = true;
						})
						if (fn) fn(isUserDefault)
					}
				})
			},



		},
		mounted: function() {
			this.getBpmDetailData()
			this.getBillData()
			this.getlogData()
		}
	})
}())
